import React, { useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { showRecord } from '@/services/ant-design-pro/api';
import { message } from 'antd';
import { useCurrentUser } from '@/pages/useCurrentUser';
import { useHistory } from 'umi'; // 关键：引入 useHistory

type RecordItem = {
  originalName: string;
  originalCodeFileUrl: string;
  optimizedCodeFileUrl: string;
  reportUrl: string;
  createTime: string;
};

const UserListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { user, loading } = useCurrentUser();
  const history = useHistory(); // 获取 history 对象
  const columns: ProColumns<RecordItem>[] = [
    {
      title: '文件名称',
      dataIndex: 'originalName',
      key: 'originalName',
      copyable: true,
      sorter: (a, b) => a.originalName.localeCompare(b.originalName),
      render: (text) => <a>{text}</a>,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      valueType: 'date',
      sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            // 跳转并传参
            history.push({
              pathname: '/code-comparison',
              query: {
                sourceUrl: record.originalCodeFileUrl,
                optimizedUrl: record.optimizedCodeFileUrl,
                reportUrl: record.reportUrl,
              },
            });
          }}
        >
          查看
        </a>,
      ],
    },
  ];

  if (loading) {
    return <PageContainer loading />;
  }

  if (!user) {
    return <PageContainer>请先登录</PageContainer>;
  }

  const fetchData = async (params: any) => {
    try {
      const response = await showRecord({
        userAccount: user?.userAccount,
      });

      if (response.code === 0) {
        let records: RecordItem[] = (response.data || []).map(
          (item: RecordItem, index: number) => ({
            ...item,
            id: index + 1,
          }),
        );

        // 文件名搜索
        if (params.originalName) {
          records = records.filter((item) =>
            item.originalName.toLowerCase().includes(params.originalName.toLowerCase()),
          );
        }

        // 日期搜索
        if (params.createTime) {
          const targetDate = new Date(params.createTime);
          const targetDayStart = new Date(targetDate);
          const targetDayEnd = new Date(targetDate);
          targetDayStart.setHours(0, 0, 0, 0);
          targetDayEnd.setHours(23, 59, 59, 999);

          records = records.filter((item) => {
            const itemTime = new Date(item.createTime).getTime();
            return itemTime >= targetDayStart.getTime() && itemTime <= targetDayEnd.getTime();
          });
        }

        return {
          data: records,
          success: true,
          total: records.length,
        };
      }

      message.error(response.message || '获取数据失败');
      return {
        data: [],
        success: false,
      };
    } catch (error) {
      console.error('API请求错误:', error);
      return {
        data: [],
        success: false,
      };
    }
  };

  return (
    <PageContainer>
      <ProTable<RecordItem>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params) => {
          return fetchData(params);
        }}
        pagination={{ pageSize: 10 }}
        search={{ labelWidth: 'auto' }}
      />
    </PageContainer>
  );
};

export default UserListPage;
